﻿using Quartz.Impl.Triggers;
using Quartz.Impl;
using Quartz.NET.Web.Extensions;
using Quartz.NET.Web.Models;
using System.Reflection;
using System.Threading.Tasks;
using System;
using Quartz.NET.Web.Tasks;

namespace Quartz.NET.Web.Utility
{
    /// <summary>
    /// 内部任务执行器，用于直接执行系统内部的业务逻辑
    /// </summary>
    public class InternalJob : IJob
    {
        private readonly IServiceProvider _serviceProvider;

        public InternalJob(IServiceProvider serviceProvider)
        {
            _serviceProvider = serviceProvider;
        }

        public async Task Execute(IJobExecutionContext context)
        {
            DateTime dateTime = DateTime.Now;
            TaskOptions taskOptions = context.GetTaskOptions();
            string executeMessage = "";
            AbstractTrigger trigger = (context as JobExecutionContextImpl).Trigger as AbstractTrigger;

            if (taskOptions == null)
            {
                FileHelper.WriteFile(FileQuartz.LogPath + trigger.Group, $"{trigger.Name}.txt", 
                    "未到找作业或可能被移除", true);
                return;
            }

            Console.WriteLine($"内部作业[{taskOptions.TaskName}]开始:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:sss")}");

            if (string.IsNullOrEmpty(taskOptions.ClassFullName))
            {
                FileHelper.WriteFile(FileQuartz.LogPath + trigger.Group, $"{trigger.Name}.txt", $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:sss")}未配置类名,", true);
                return;
            }

            try
            {
                // 尝试通过类名获取类型
                Type jobType = Type.GetType(taskOptions.ClassFullName);

                if (jobType == null)
                {
                    // 如果找不到类型，尝试从所有已加载的程序集中查找
                    foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
                    {
                        jobType = assembly.GetType(taskOptions.ClassFullName);
                        if (jobType != null)
                            break;
                    }
                }

                if (jobType == null)
                {
                    executeMessage = $"找不到类型: {taskOptions.ClassFullName}";
                }
                else
                {
                    // 检查类型是否继承自TaskBase
                    if (!typeof(TaskBase).IsAssignableFrom(jobType))
                    {
                        executeMessage = $"类型 {taskOptions.ClassFullName} 未继承自TaskBase抽象类";
                        Console.WriteLine(executeMessage);
                        FileHelper.WriteFile(FileQuartz.LogPath + taskOptions.GroupName + "\\", $"{taskOptions.TaskName}.txt",
                            $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}_{dateTime.ToString("yyyy-MM-dd HH:mm:ss")}_{executeMessage}\r\n", true);
                        return;
                    }

                    // 尝试从依赖注入容器获取实例
                    object jobInstance = _serviceProvider.GetService(jobType);

                    // 如果依赖注入容器中没有注册，则尝试手动创建实例
                    if (jobInstance == null)
                    {
                        jobInstance = Activator.CreateInstance(jobType);
                    }

                    // 执行TaskBase的Execute方法
                    if (jobInstance is TaskBase taskBase)
                    {
                        await taskBase.Execute();
                        executeMessage = "OK";
                    }
                    else
                    {
                        executeMessage = $"无法将类型 {taskOptions.ClassFullName} 转换为TaskBase";
                    }

                    #region 未约束必须继承TaskBase
                    //// 查找名为 Execute 的方法
                    //MethodInfo executeMethod = jobType.GetMethod("Execute");
                    //if (executeMethod != null)
                    //{
                    //    // 执行方法
                    //    object result = executeMethod.Invoke(jobInstance, null);

                    //    // 处理可能的异步方法
                    //    if (result is Task task)
                    //    {
                    //        await task;
                    //    }

                    //    executeMessage = "OK";
                    //}
                    //else
                    //{
                    //    executeMessage = $"类型 {taskOptions.ClassFullName} 没有 Execute 方法";
                    //}
                    #endregion
                }
            }
            catch (Exception ex)
            {
                executeMessage = ex.Message;
                if (ex.InnerException != null)
                {
                    executeMessage += " -> " + ex.InnerException.Message;
                }
            }

            try
            {
                string logContent = $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}_{dateTime.ToString("yyyy-MM-dd HH:mm:ss")}_{(string.IsNullOrEmpty(executeMessage) ? "OK" : executeMessage)}\r\n";
                FileHelper.WriteFile(FileQuartz.LogPath + taskOptions.GroupName + "\\", $"{taskOptions.TaskName}.txt", logContent, true);
            }
            catch (Exception)
            {
                // 记录日志失败，忽略异常
            }

            Console.WriteLine(trigger.FullName + " " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:sss") + " " + executeMessage);
            return;
        }
    }
}
